package com.ellecity06.debugtools.ui.request_details

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.ellecity06.debugtools.R
import com.ellecity06.debugtools.base.BaseDebugActivity
import com.ellecity06.debugtools.databinding.DebugActivityRequestDetailBinding
import com.ellecity06.debugtools.db.DebugToolsDatabase
import com.ellecity06.debugtools.db.dao.RequestDao
import com.ellecity06.debugtools.db.entity.RequestEntity
import com.ellecity06.debugtools.utils.TimeUtils
import com.ellecity06.debugtools.utils.UnitUtils
import com.ellecity06.debugtools.widgets.dialog.showAlert
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2023/4/21 11:38
 * @des 接口请求详情
 */
internal class DebugRequestDetailActivity :
    BaseDebugActivity<DebugActivityRequestDetailBinding, DebugRequestDetailViewModel>() {
    private val dao: RequestDao by lazy { DebugToolsDatabase.getDatabase(this).getRequestDao() }
    private val requestId: Int by lazy { intent.getIntExtra(INTENT_ID, 0) }
    private val adapter by lazy { DebugDetailAdapter() }

    companion object {
        private const val INTENT_ID = "intent_id"
        fun launch(fragment: Fragment, id: Int) {
            fragment.startActivityForResult(
                Intent(
                    fragment.requireActivity(),
                    DebugRequestDetailActivity::class.java
                ).apply {
                    putExtra(
                        INTENT_ID,
                        id
                    )
                }, 101
            )
        }
    }

    override fun inflateBinding(): DebugActivityRequestDetailBinding {
        return DebugActivityRequestDetailBinding.inflate(layoutInflater)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.debug_text_request_title))
        baseBinding.ivRight.setImageResource(R.mipmap.debug_icon_share)
        baseBinding.ivRight.setOnClickListener {
            lifecycleScope.launchWhenCreated {
                val item = dao.findById(requestId)
                val str = StringBuilder().apply {
                    append("请求地址：").append(item?.url).append("\n")
                    append("Method：").append(item?.method).append("\n")
                    append("发起请求时间：").append(TimeUtils.getDate("yyyy-MM-dd HH:mm:ss:SSS", item?.sentRequestAtMillis ?: 0)).append("\n")
                    append("得到结果时间：").append(TimeUtils.getDate("yyyy-MM-dd HH:mm:ss:SSS", item?.receivedResponseAtMillis ?: 0)).append("\n")

                    val timeConsuming =
                        if (item!!.receivedResponseAtMillis != null && item.sentRequestAtMillis != null) {
                            UnitUtils.timeUnit(item.receivedResponseAtMillis!! - item.sentRequestAtMillis!!)
                        } else "--"
                    append("耗时：").append(timeConsuming).append("\n")
                    append("请求头：").append(item.requestHeader).append("\n")
                    append("请求参数：").append(item.requestBody).append("\n")
                    append("请求结果：").append(item.responseBody).append("\n")
                }
                if (str.length>4000){
                    Toast.makeText(this@DebugRequestDetailActivity,"文本太长啦，请长按复制自行分享!",Toast.LENGTH_LONG).show()
                    return@launchWhenCreated
                }
                val share = Intent(Intent.ACTION_SEND)
                share.type = "text/plain"
                share.putExtra(Intent.EXTRA_TEXT, str.toString())
                startActivity(Intent.createChooser(share, "接口分享："))
            }

        }
        binding.rv.layoutManager = LinearLayoutManager(this)
        binding.rv.adapter = adapter
        lifecycleScope.launchWhenCreated {
            viewModel.data.collectLatest {
                adapter.submitData(it)
            }
        }
    }

    private fun delete() {
        showAlert("确定要永久删除全部数据吗") {
            lifecycleScope.launch {
                dao.deleteById(requestId)
                setResult(Activity.RESULT_OK)
                finish()
            }
        }
    }

    override fun initViewModel(): DebugRequestDetailViewModel {
        return ViewModelProvider(this, factory = DaoViewModelFactory {
            DebugRequestDetailViewModel(dao, requestId)
        })[DebugRequestDetailViewModel::class.java]
    }
}